import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;

/**
 * @author ZhiWen Ren
 * @version 1.0
 * @description: LeetCode-994-腐烂的橘子
 * @date 2025/4/24 20:53
 */
public class Solution994 {

    // 上下左右
    private int[] x = {1, -1, 0, 0};
    private int[] y = {0, 0, -1, 1};

    public int orangesRotting(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int ans = 0;

        Queue<Integer> queue = new ArrayDeque<>();
        Map<Integer, Integer> time = new HashMap<>();

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 2) {
                    int code = i * n + j;
                    queue.add(code);
                    time.put(code, 0);
                }
            }
        }

        while (!queue.isEmpty()) {
            // 使用queue实现多源广度优先搜索
            int code = queue.remove();
            int r = code / n;
            int c = code % n;

            for (int i = 0; i < 4; i++) {
                int row = r + x[i];
                int col = c + y[i];
                if (row >= 0 && row < m && col >= 0 && col < n && grid[row][col] == 1) {
                    // 污染这个橘子，并记录这个橘子被污染的时间
                    grid[row][col] = 2;
                    int ncode = row * n + col;
                    queue.add(ncode);
                    time.put(ncode, time.get(code) + 1);
                    ans = time.get(ncode);
                }
            }
        }

        for (int[] row : grid) {
            for (int orange : row) {
                if (orange == 1) {
                    // 仍然有橘子没有被污染
                    return -1;
                }
            }
        }
        return ans;
    }
}

